/**
 * 
 */
package com.wedroid.r2d2.http;

import java.util.concurrent.TimeUnit;

import org.apache.http.conn.HttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lute
 *
 */
public class IdleConnectionMonitor extends Thread {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    
    private final HttpClientConnectionManager manager;

    private volatile boolean shutdown;

    /**
     * @param manager
     */
    public IdleConnectionMonitor(HttpClientConnectionManager manager) {
        super();
        this.manager = manager;
    }

    /* (non-Javadoc)
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        try {
            while (!shutdown) {
                synchronized (this) {
                    wait(5000);
                    logger.debug("#run - Going to close expired and idle connections...");
                    manager.closeExpiredConnections();
                    manager.closeIdleConnections(30, TimeUnit.SECONDS);
                }
            }
        } catch (InterruptedException e) {
            logger.error("#run - IdleConnectionMonitor encounters InterruptedException: {}", e);
            shutdown();
        }
    }

    public void shutdown() {
        shutdown = true;
        synchronized (this) {
            notifyAll();
        }
    }

}
